package com.example.lincoln.renderscriptdemo;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Handler;
import android.os.SystemClock;
import android.renderscript.Allocation;
import android.renderscript.Element;
import android.renderscript.RenderScript;
import android.renderscript.ScriptIntrinsicBlur;
import android.renderscript.Type;
import android.util.Log;

/**
 * Created by Lincoln on 2016-11-17.
 * 图片高斯模糊工具类
 * 配合压缩图片模糊效率更高,方法如下
 * BitmapFactory.Options options = new BitmapFactory.Options();
 * options.inSampleSize = 2; // 设置它的压缩率，表示压缩1/2
 * mBitmap = BitmapFactory.decodeResource(this.getResources(), R.drawable.bg, options);
 */

public class RenderscriptUtil {

    /**高斯模糊**/
    public static void blurBitmap(final Context context, final Bitmap bitmap, final float radius, final CallbackListener callbackListener) {
        final Handler mHandler = new Handler();
        new Thread(new Runnable() {
            @Override
            public void run() {
                long mTimeStart = SystemClock.currentThreadTimeMillis();
                startBlurBitmap(bitmap, radius, context);
                Log.e("blurBitmapUserTime", "耗时：" + (SystemClock.currentThreadTimeMillis() - mTimeStart));
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        // 回调onHandlerResponse方法
                        callbackListener.onBitmapResponse(bitmap);
                    }
                });
            }
        }).start();
    }

    private static Bitmap startBlurBitmap(Bitmap bitmap, float radius, Context context) {
        if (radius > 25) {
            Log.e("radius", "Set blur radius (maximum 25.0)");
            radius = 25;
        }
        // 初始化Renderscript，这个类提供了RenderScript context，
        // 在创建其他RS类之前必须要先创建这个类，他控制RenderScript的初始化，资源管理，释放
        RenderScript rs = RenderScript.create(context);

        //Create allocation from Bitmap
        Allocation allocation = Allocation.createFromBitmap(rs, bitmap);

        Type t = allocation.getType();

        //Create allocation with the same type
        Allocation blurredAllocation = Allocation.createTyped(rs, t);

        // 创建高斯模糊对象
        ScriptIntrinsicBlur blurScript = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs));
        // 设定模糊度(maximum 25.0)
        blurScript.setRadius(radius);
        //Set input for script
        blurScript.setInput(allocation);
        //Call script for output allocation
        blurScript.forEach(blurredAllocation);

        //Copy script result into bitmap
        blurredAllocation.copyTo(bitmap);

        //Destroy everything to free memory
        allocation.destroy();
        blurredAllocation.destroy();
        blurScript.destroy();
        t.destroy();
        rs.destroy();
        return bitmap;
    }

    interface CallbackListener {
        void onBitmapResponse(Bitmap bitmap);
    }
}
